package com.mlick.dddk.utils;

/**
 * Created by mlick on 2018-03-22.
 */

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import android.util.Log;

/**
 * Android运行linux命令
 */
public final class RootCmd {
    private static final String TAG = "RootCmd";
    private static boolean mHaveRoot = false;

    /**
     * 判断机器Android是否已经root，即是否获取root权限
     */
    public static boolean haveRoot() {
        if (!mHaveRoot) {
            int ret = execRootCmdSilent("echo test"); // 通过执行测试命令来检测
            if (ret != -1) {
                Log.i(TAG, "have root!");
                mHaveRoot = true;
            } else {
                Log.i(TAG, "not root!");
            }
        } else {
            Log.i(TAG, "mHaveRoot = true, have root!");
        }
        return mHaveRoot;
    }

    public static void tapPhone(int x, int y) throws Exception {
        runCmd(String.format("input tap %d %d", x, y));
    }

    public static void swipePhone(int sx, int sy, int ex, int ey) throws Exception {
        runCmd(String.format("input touchscreen swipe %d %d %d %d", sx, sy, ex, ey));
    }

    public static String runCmd(String cmd) throws Exception {
        if (!getIsPower()) {
            System.out.print("开启亮屏");
            //            openOrClosePower();
            openOrClosePower();
            sleepTime(3);
            //            TimeUnit.SECONDS.sleep(2);
            // 3 上滑解锁
            System.out.print("上滑解锁");
            swipePhone(365, 810, 365, 200);
            //            TimeUnit.SECONDS.sleep(2);
            sleepTime(3);
        }
        return execRootCmd(cmd);
    }

    /**
     * 执行命令并且输出结果
     */
    public static String execRootCmd(String cmd) {
        String result = "";
        DataOutputStream dos = null;
        DataInputStream dis = null;

        try {
            Process p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令
            dos = new DataOutputStream(p.getOutputStream());
            dis = new DataInputStream(p.getInputStream());

            Log.i(TAG, cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            String line = null;

            while ((line = dis.readLine()) != null) {
                Log.d("===result", line);
                result += line;
            }
            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 执行命令但不关注结果输出
     */
    public static int execRootCmdSilent(String cmd) {
        int result = -1;
        DataOutputStream dos = null;

        try {
            Process p = Runtime.getRuntime().exec("su");

            readSuccess(p);

            dos = new DataOutputStream(p.getOutputStream());

            Log.i(TAG, cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            p.waitFor();
            result = p.exitValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static List<String> readSuccess(Process proc) throws IOException {
        //        logger.info("readSuccess---------->");
        List<String> strs = new ArrayList<>();

        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin, "GBK");

        BufferedReader br = new BufferedReader(isr);
        String line = null;

        while ((line = br.readLine()) != null) {
            SysUtils.out("out ===>" + line);
            strs.add(line);
        }
        //        logger.info("=================");
        return strs;
    }

    public static void openOrClosePower() throws IOException {
        execRootCmd("input keyevent 26");
    }

    // false 表示屏幕关闭 || true 表示屏幕亮起
    public static boolean getIsPower() throws IOException {
        //Process process = Runtime.getRuntime().exec("su dumpsys power|findstr \"mScreenOn=\" \n");
        //List<String> list = readSuccess(process);
        //process.destroy();
        //String cmdr = list != null && list.size() > 0 ? list.get(0) : null;
        ////        runCmd("adb shell dumpsys power|findstr \"mScreenOn=\"");
        String cmdr = execRootCmd("dumpsys power|grep \"mScreenOn=\"");
        if (cmdr != null && "true".equals(cmdr.split("=")[1])) {
            return true;
        }
        return false;
    }

    static void sleepTime(int i, boolean b) throws InterruptedException {
        for (int j = 0; j < i; j++) {
            System.out.print(".");
            TimeUnit.SECONDS.sleep(1);
        }
        if (b) {
            SysUtils.out("");
        }
    }


    static void sleepTime(int i) throws InterruptedException {
        sleepTime(i, true);
    }
}